<script setup lang="ts">
import { UploadFileAPI } from '@/apis/common';
import { BuildAPI, deleteParkAPI, delRentAPI, exitRentAPI, getRentDetailAPI, parkAPI, rentBUildAPI } from '@/apis/park';
import type { BuildParams, parkParams, RentBuildRes, RentDetialRes, Row } from '@/types/park';
import { ElMessage, ElMessageBox,  type FormInstance, type FormRules, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
const disabledDate = (time: Date) => {
  // 不能小于今日日期，包含今天 （ 1000 * 60 * 60 * 24 -> 1天的毫秒数 ）
  if(buildParams.value.startTime){
    return time.getTime() < +new Date(buildParams.value.startTime) - 1000 * 60 * 60 * 24
  }
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}
const buildParams = ref<BuildParams>({
  buildingId: undefined,
  contractId: undefined,
  contractUrl: '',
  endTime: '',
  enterpriseId: undefined,
  startTime: '',
  type: 0
})
const buildRules = ref<FormRules<BuildParams>>({
  buildingId: [
    { required: true, message: '请选择租赁楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁起止日期', trigger: 'blur' }
  ],
  contractId: [
    { required: true, message: '请上传租赁合同', trigger: 'change' }
  ]
})
const param = ref<parkParams>({
  name: '',
  page: 1,
  pageSize: 10
})


interface RentRes extends Row {
  rowDetail: RentDetialRes[]
}


const reslist = ref<RentRes[]>([])
const total = ref(0)
const getList = async () => {
  const res = await parkAPI(param.value)
  reslist.value = res.data.rows.map(item => ({ ...item, rowDetail: [] }))
  total.value = res.data.total
}
getList()
const onSelect = () => {
  param.value.page = 1
  getList()
}
const buildForm = ref<FormInstance>()
const onDelete = async (id: number) => {
  await deleteParkAPI(id)
  getList()
  ElMessage.success('删除成功')
}
const dialogShow = ref(false)
const closeDialog = () => {
  dialogShow.value = false
  buildForm.value?.resetFields()
  rentDate.value = []
  buildParams.value = {
    buildingId: undefined,
    contractId: undefined,
    contractUrl: '',
    endTime: '',
    enterpriseId: 0,
    startTime: '',
    type: 0
  }
  filelist.value = []
}
const openDialog = (id: number) => {
  dialogShow.value = true
  buildParams.value.enterpriseId = id
}
const rentBuildId = ref<RentBuildRes[]>([])
onMounted(async () => {
  const res = await rentBUildAPI()
  rentBuildId.value = res.data
})
const rentDate = ref([])
watch(rentDate, () => {
  if (rentDate.value) {
    buildParams.value.startTime = rentDate.value[0]
    buildParams.value.endTime = rentDate.value[1]
  } else {
    buildParams.value.startTime = ''
    buildParams.value.endTime = ''
  }
})
const detailRent = async (rowSon: RentDetialRes,row:RentRes) => {
  ElMessageBox.confirm('此操作将删除合同, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async()=>{
    await delRentAPI(rowSon.id)
    row.rowDetail=row.rowDetail.filter(item=>item.id!==rowSon.id)
  }).catch (()=> {})
}
const outRent = async (rowSon: RentDetialRes) => {
  ElMessageBox.confirm('此操作将取消租赁, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async()=>{
    await exitRentAPI(rowSon.id)
    rowSon.status=3
  }).catch (()=> {})
}
 // await BuildAPI()
//  ElMessage.success('续租成功')
const renewRent = async (rowSon: RentDetialRes,row:RentRes) => {
    rentBuildId.value.push({
      id:Number(rowSon.buildingId),
      name:rowSon.buildingName
    })
    buildParams.value.buildingId=Number(rowSon.buildingId)
    buildParams.value.startTime=rowSon.endTime
    buildflag.value=true
   openDialog(row.id)
}
const buildflag=ref(false)
const buildRent = async () => {
  if(buildflag.value){
  buildParams.value.type=1
  await buildForm.value?.validate()
    try {
    await BuildAPI(buildParams.value)
    ElMessage.success('续租成功')
    closeDialog()
  } catch (err) {
    console.log(err);
  }finally{
    buildflag.value=false
  }
  }else{
  await buildForm.value?.validate()
    try {
    await BuildAPI(buildParams.value)
    ElMessage.success('租赁成功')
    closeDialog()
  } catch (err) {
    console.log(err);
  }
  }
}
const upload = async (options: UploadRequestOptions) => {
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')
  const res = await UploadFileAPI(fd)
  buildParams.value.contractUrl = res.data.url
  buildParams.value.contractId = res.data.id
  buildForm.value?.validateField('contractId')
  return res.data.url
}
const filelist = ref<UploadUserFile[]>([])
const onRemove = () => {
  buildParams.value.contractUrl = ''
  buildParams.value.contractId = undefined
  buildForm.value?.validateField('contractId')
}

const expandChange = async (row: any) => {
  const res = await getRentDetailAPI(row.id)
  console.log(res.data);
  row.rowDetail = res.data
}
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input clearable placeholder="请输入内容" class="search-main" v-model="param.name" @clear="getList" />
      <el-button type="primary" @click="onSelect">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/addpark')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="reslist" @expand-change="expandChange" row-key="id">
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-table :data="row.rowDetail">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="{ row }">
                  <!-- 合同的租赁状态0待生效1生效中2已到期3已退租 -->
                  <el-tag v-if="row.status === 0" type="info">待生效</el-tag>
                  <el-tag v-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-if="row.status === 2" type="warning">已到期</el-tag>
                  <el-tag v-if="row.status === 3" type="danger">已退租</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{ row: rowSon }">
                  <el-button size="small" type="primary" link @click="renewRent(rowSon,row)">续租</el-button>
                  <el-button size="small" type="primary" link :disabled="rowSon.status === 3" @click="outRent(rowSon)">退租</el-button>
                  <el-button size="small" type="primary" link :disabled="rowSon.status !== 3" @click="detailRent(rowSon,row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column prop="demoFlag" label="操作" width="200px">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="openDialog(row.id)">添加合同</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/prisedetail/${row.id}`)">查看</el-button>
            <el-button size="small" type="primary" link @click="$router.push(`/addpark/${row.id}`)">编辑</el-button>
            <el-button size="small" type="primary" link @click="onDelete(row.id)">删除</el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination :total="total" :page-sizes="[2, 5, 10]" v-model:page-size="param.pageSize"
        v-model:current-page="param.page" @change="getList" layout="total,sizes, prev, pager, next,jumper" />
    </div>
  </div>
  <el-dialog title="添加合同" v-model="dialogShow" width="580px">
    <div class="form-container">
      <el-form ref="buildForm" :model="buildParams" label-position="top" :rules="buildRules">
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select v-model="buildParams.buildingId" placeholder="请选择" clearable>
            <el-option v-for="item in rentBuildId" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="endTime">
          <el-date-picker v-model="rentDate" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
        </el-form-item>
        <el-form-item label="租赁合同" prop="contractId">
          <el-upload accept=".doc, .pdf" :http-request="upload" @remove="onRemove" :file-list="filelist">
            <el-button size="small" type="primary" plain>上传合同文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="buildRent">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>